package com.ty.user.starter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ty.user.starter.entity.UserRole;
import com.ty.user.starter.entity.dto.UserRoleDto;
import com.ty.user.starter.mapper.RoleMapper;
import com.ty.user.starter.mapper.UserMapper;
import com.ty.user.starter.mapper.UserRoleMapper;
import com.ty.user.starter.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * <p>
 * 用户-角色表 服务实现类
 * </p>
 *
 * @author minku
 * @since 2021-10-17
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(UserRoleDto dto) {
        this.delete(dto.getUserId());
        // 验证角色集合中是否存在重复的角色信息
        long count = dto.getRoleIds().parallelStream().distinct().count();
        Assert.isTrue(dto.getRoleIds().size() == count, "角色信息重复设置");
        // 验证角色信息是否存在
        for (Long roleId : dto.getRoleIds()) {
            Assert.notNull(roleMapper.selectById(roleId), String.format("角色id: %d 不存在", roleId));
        }
        // 异步循环保存
        dto.getRoleIds().parallelStream().forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(dto.getUserId());
            userRole.setRoleId(roleId);
            baseMapper.insert(userRole);
        });
    }


    /**
     * 尝试删除用户对应的角色信息
     *
     * @param userId 用户id
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(long userId) {
        Assert.notNull(userMapper.selectById(userId), "用户信息不存在");
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.eq("user_id", userId);
        baseMapper.delete(query);
    }
}
